package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.commom.base.BaseApp;
import com.bw.gmall.realtime.commom.bean.TradeSkuOrderBean;
import com.bw.gmall.realtime.commom.constant.Constant;
import com.bw.gmall.realtime.commom.function.DorisMapFunction;
import com.bw.gmall.realtime.commom.util.DateFormatUtil;
import com.bw.gmall.realtime.commom.util.FlinkSinkUtil;
import com.bw.gmall.realtime.commom.util.HbaseUtil;
import com.bw.gmall.realtime.commom.util.RedisUtil;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.AsyncConnection;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class DwsTradeSkuOrderAsyncCacheWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeSkuOrderAsyncCacheWindow().start(Constant.TOPIC_DWD_TRADE_ORDER_DETAIL,Constant.TOPIC_DWD_TRADE_ORDER_DETAIL,4,10029);

    }

    //12.9交易域SKU粒度下单各窗口汇总表
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        // 1、ETL数据
        SingleOutputStreamOperator<JSONObject> etlStream = dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    // 因为有撤回流,所有要过滤
                    if (s != null) {
                        JSONObject jsonObject = JSON.parseObject(s);
                        String skuId = jsonObject.getString("sku_id");
                        Long ts = jsonObject.getLong("ts");
                        if (skuId != null && ts != null) {
                            jsonObject.put("ts", ts * 1000);
                            collector.collect(jsonObject);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


        // 2、添加水位线
        SingleOutputStreamOperator<JSONObject> watermarksStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));

        // 3、处理回撤流
        /**
         *    sku_id  category3_id  money
         *     10       20           30            开启定时器(10S)  liststate
         *     10       20           20                          liststate
         *     10       20           10                          liststate
         *                                        定时器触发 ---->取liststate最后一条
         *
         *
         * order_id 作为key
         *   sku_id  category3_id  money          状态     下游
         *   10       20           30             30       30
         *   10       20           20             20      -10
         *   10       20           10             10      -10
         *
         *
         *
         */
        SingleOutputStreamOperator<TradeSkuOrderBean> processStream = watermarksStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("sku_id");
            }
        }).process(new KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>() {
            private MapState<String, BigDecimal> mapState;

            // 金额这种类型，不会用Float，也不会用Double,基本都用BigDecimal
            @Override
            public void open(Configuration parameters) throws Exception {
                MapStateDescriptor<String, BigDecimal> stateDescriptor = new MapStateDescriptor<String, BigDecimal>("order_state", String.class, BigDecimal.class);
                stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(30L)).build());
                mapState = getRuntimeContext().getMapState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>.Context context, Collector<TradeSkuOrderBean> collector) throws Exception {
                // 从状态里面取值
                BigDecimal split_total_amount = mapState.get("splitTotalAmount");// 分摊金额
                BigDecimal split_activity_amount = mapState.get("splitActivityAmount");// 活动金额
                BigDecimal split_coupon_amount = mapState.get("splitCouponAmount");// 优惠券金额
                BigDecimal original_amount = mapState.get("originalAmount");// 原始金额

                split_total_amount = split_total_amount == null ? new BigDecimal(0) : split_total_amount;
                split_activity_amount = split_activity_amount == null ? new BigDecimal(0) : split_activity_amount;
                split_coupon_amount = split_coupon_amount == null ? new BigDecimal(0) : split_coupon_amount;
                original_amount = original_amount == null ? new BigDecimal(0) : original_amount;


                // 从数据取出这金额

                BigDecimal splitTotalAmount = jsonObject.getBigDecimal("split_total_amount");
                BigDecimal splitActivityAmount = jsonObject.getBigDecimal("split_activity_amount");
                BigDecimal splitCouponAmount = jsonObject.getBigDecimal("split_coupon_amount");

                BigDecimal sku_num = jsonObject.getBigDecimal("sku_num");
                BigDecimal orderPrice = jsonObject.getBigDecimal("order_price");

                // 计算原始金额
                BigDecimal originalAmount = orderPrice.multiply(sku_num);


                // 直接往下游发
                String skuId = jsonObject.getString("sku_id");
                String skuName = jsonObject.getString("sku_name");
                String id = jsonObject.getString("id");
                Long ts = jsonObject.getLong("ts");

                collector.collect(TradeSkuOrderBean.builder()
                        .skuId(skuId)
                        .skuName(skuName)
                        .activityReduceAmount(splitActivityAmount.subtract(split_activity_amount))
                        .couponReduceAmount(splitCouponAmount.subtract(split_coupon_amount))
                        .originalAmount(originalAmount.subtract(original_amount))
                        .orderAmount(splitTotalAmount.subtract(split_total_amount))
                        .orderDetailId(id)
                        .ts(ts)
                        .build());

            }
        });

        // 4、根据SKU keyby
        // 5、 聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> reduceStream = processStream.keyBy(new KeySelector<TradeSkuOrderBean, String>() {
                    @Override
                    public String getKey(TradeSkuOrderBean tradeSkuOrderBean) throws Exception {
                        return tradeSkuOrderBean.getSkuId();
                    }
                }).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean reduce(TradeSkuOrderBean t1, TradeSkuOrderBean t2) throws Exception {
                        t1.setActivityReduceAmount(t1.getActivityReduceAmount().add(t2.getActivityReduceAmount()));
                        t1.setCouponReduceAmount(t1.getCouponReduceAmount().add(t2.getCouponReduceAmount()));
                        t1.setOriginalAmount(t1.getOriginalAmount().add(t2.getOriginalAmount()));
                        t1.setOrderAmount(t1.getOrderAmount().add(t2.getOrderAmount()));
                        return t1;
                    }
                }, new WindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<TradeSkuOrderBean> iterable, Collector<TradeSkuOrderBean> collector) throws Exception {
                        String start = DateFormatUtil.tsToDate(timeWindow.getStart());
                        String end = DateFormatUtil.tsToDate(timeWindow.getEnd());
                        String curDate = DateFormatUtil.tsToDate(System.currentTimeMillis());


                        Iterator<TradeSkuOrderBean> iterator = iterable.iterator();
                        while (iterator.hasNext()) {
                            TradeSkuOrderBean tradeSkuOrderBean = iterator.next();
                            tradeSkuOrderBean.setStt(start);
                            tradeSkuOrderBean.setEdt(end);
                            tradeSkuOrderBean.setCurDate(curDate);
                            collector.collect(tradeSkuOrderBean);
                        }

                    }
                });
        // 6、关联Hbase维度

        // 关联SKU
        SingleOutputStreamOperator<TradeSkuOrderBean> dimStream = AsyncDataStream.unorderedWait(reduceStream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private  StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String skuId = tradeSkuOrderBean.getSkuId();
                String redisKey = RedisUtil.getRedisKey("dim_sku_info", skuId);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {

                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        return JSONObject.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        JSONObject dimSkuInfo =  null;
                        if(jsonObject == null){// 如果Redis没有查出来
                            try {
                                // 从Hbase中查
                                dimSkuInfo = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_sku_info", skuId);
                                // 放到Redis当中
                                redisAsyncConnection.async().setex(redisKey,24*60*60,JSON.toJSONString(dimSkuInfo));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }else{// 从Redis中查出来了
                            dimSkuInfo  = jsonObject;
                        }
                        return dimSkuInfo;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setSpuId(jsonObject.getString("spu_id"));
                            tradeSkuOrderBean.setTrademarkId(jsonObject.getString("tm_id"));
                            tradeSkuOrderBean.setCategory3Id(jsonObject.getString("category3_id"));
                        } else {
                            System.out.println("\"未查找维度\" = " + "未查找维度");
                        }
                    }
                });

            }
        }, 1000, TimeUnit.MILLISECONDS);

        // 关联SPU
        SingleOutputStreamOperator<TradeSkuOrderBean> dimStream1 = AsyncDataStream.unorderedWait(dimStream, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private  StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String spuId = tradeSkuOrderBean.getSpuId();
                String redisKey = RedisUtil.getRedisKey("dim_spu_info", spuId);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {

                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                        return JSONObject.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        JSONObject dimSpuInfo =  null;
                        if(jsonObject == null){// 如果Redis没有查出来
                            try {
                                // 从Hbase中查
                                dimSpuInfo = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_spu_info", spuId);
                                // 放到Redis当中
                                redisAsyncConnection.async().setex(redisKey,24*60*60,JSON.toJSONString(dimSpuInfo));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }else{// 从Redis中查出来了
                            dimSpuInfo  = jsonObject;
                        }
                        return dimSpuInfo;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setSpuName(jsonObject.getString("name"));
                        } else {
                            System.out.println("\"未查找维度\" = " + "未查找维度");
                        }
                    }
                });

            }
        }, 1000, TimeUnit.MILLISECONDS);









        // 7、写入Doris


        dimStream.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_SKU_ORDER_WINDOW));

        /**
         * sku_id  category3_id  money
         *   10       20          100
         *   10       20          200
         *
         *   10  300 手机
         *
         */
    }
}
